﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tiscs.Practices.Web.Services.Client
{
    /// <summary>
    /// 异步操作信息基类。
    /// </summary>
    public abstract class AsyncOperationBase : OperationBase
    {
        /// <summary>
        /// 构造方法。
        /// </summary>
        /// <param name="userState">用户状态。</param>
        public AsyncOperationBase(object userState)
            : base(userState)
        {
        }

        /// <summary>
        /// 异步执行结果实例。
        /// </summary>
        protected IAsyncResult AsyncResult { get; private set; }

        /// <summary>
        /// 开始执行异步操作。
        /// </summary>
        /// <param name="callback">异步操作执行完毕回调。</param>
        /// <returns>异步执行结果实例。</returns>
        protected abstract IAsyncResult BeginCore(AsyncCallback callback);

        /// <summary>
        /// 异步执行结束方法。
        /// </summary>
        /// <param name="result">异步执行结果实例。</param>
        /// <returns>异步操作的返回数据。</returns>
        protected abstract object EndCore(IAsyncResult result);

        /// <summary>
        /// 异步操作执行完毕回调。
        /// </summary>
        /// <param name="result">异步执行结果实例。</param>
        private void HandleAsyncCompleted(IAsyncResult result)
        {
            AsyncResult = result;
            object value = null;
            try
            {
                value = EndCore(result);
            }
            catch (Exception exception)
            {
                Complete(exception);
                return;
            }
            Complete(value);
        }

        /// <summary>
        /// 开始执行异步操作。
        /// </summary>
        protected void Start()
        {
            BeginCore(HandleAsyncCompleted);
        }
    }
}
